<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;

use BackupManager\Filesystems\Destination;

class DatabaseController extends Controller
{
    protected $directory = 'backup';

    //
    public function index()
    {

        $disk = Storage::disk('public');

        // 获取目录下的文件
        $files = $disk->files($this->directory);

        $backup = [];
        foreach ($files as $k => $v) {
            if (substr($v,strpos($v,'.')+1) === 'sql') {
                $backup[$k]['filename'] = substr($v,strpos($v,'/')+1);
                $backup[$k]['filesize'] = byteToSize($disk->size($v));            //文件大小
                $backup[$k]['time'] = date('Y-m-d H:i:s', $disk->lastModified($v)); //最后修改时间
            }
        }

        return backendView('database.index', compact('backup'));
    }
    //删除
    public function delete($filename)
    {

        $disk = Storage::disk('public');

        $exists = $disk->exists($this->directory.'/'.$filename);
        if (!$exists) {
            return back()->with('error','文件不存在');
        }
        // 删除单条文件
        $result = $disk->delete($this->directory.'/'.$filename);

        if ($result) {
            return back()->with('success', __('Delete success'));
        }

        return back()->with('error', __('Delete failed'));
    }

    public function backup()
    {
        $backupdir ='backup';

        if (!Storage::disk ('public')->exists ($backupdir)){
            if (!Storage::disk ('public')->makeDirectory($backupdir)){
                return back()->with('success','数据库备份路径不存在');
            }
        }

        if (Artisan::call('db:backup --env')){
            return back()->with('success','数据库备份失败');
        }

        return back()->with('success','数据库备份成功');
    }

    public function restore($filename)
    {
        $disk = Storage::disk('public');

        $exists = $disk->exists($this->directory.'/'.$filename);
        //dd($exists);
        if (!$exists) {
            return back()->with('error','sql文件不存在');
        }

        //导入sql文件操作
        $sql = file_get_contents($disk->path($this->directory.'/'.$filename));
        $result = DB::unprepared($sql);

        if ($result != 1) {
            return back()->with('error', '数据库恢复失败');
        }

        return back()->with('success', '数据库恢复成功');
    }

    public function download($filename)
    {

        $disk = Storage::disk('public');

        $exists = $disk->exists($this->directory.'/'.$filename);
        if (!$exists) {
            return back()->with('error','文件不存在');
        }

        //完整路径下载
        return response()->download($disk->path($this->directory.'/'.$filename));
    }

}
